package com.chengxiaoxiao.libarypartner.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.chengxiaoxiao.libarypartner.R;
import com.chengxiaoxiao.libarypartner.constants.AppConsrants;
import com.chengxiaoxiao.libarypartner.utils.ApiAddress;
import com.chengxiaoxiao.libarypartner.utils.LoadDialogUtils;
import com.chengxiaoxiao.libarypartner.utils.SPUtils;
import com.chengxiaoxiao.libarypartner.utils.ToastUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.image.SmartImageView;

import org.apache.http.Header;
import org.json.JSONObject;

public class BookActivity extends Activity
{
    private com.loopj.android.image.SmartImageView imageBook;
    private TextView textBookName;
    private TextView textNumber;
    private TextView textPrice;
    private TextView textAuthor;
    private TextView textPublisher;
    private TextView textCatrgory;
    private TextView textISBN;
    private TextView textAddress;
    private TextView textDescript;
    private TextView textSmallDescript;


    String bookId;
    int bookNumber = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book);

        initView();


        Intent intent = getIntent();
        bookId = intent.getStringExtra(AppConsrants.BOOK_ID);

        if ("".equalsIgnoreCase(bookId))
        {
            ToastUtils.makeText(BookActivity.this, "系统开小差了，请重试~");
            return;
        }
        LoadDialogUtils.show(BookActivity.this,"","加载中...");

        initBook(bookId);


    }

    /**
     * 加载UI
     */
    private void initView()
    {
        imageBook = (SmartImageView) findViewById(R.id.imageBook);
        textBookName = (TextView) findViewById(R.id.textBookName);
        textNumber = (TextView) findViewById(R.id.textNumber);
        textPrice = (TextView) findViewById(R.id.textPrice);
        textAuthor = (TextView) findViewById(R.id.textAuthor);
        textPublisher = (TextView) findViewById(R.id.textPublisher);
        textCatrgory = (TextView) findViewById(R.id.textCatrgory);
        textISBN = (TextView) findViewById(R.id.textISBN);
        textAddress = (TextView) findViewById(R.id.textAddress);
        textDescript = (TextView) findViewById(R.id.textDescript);
        textSmallDescript = (TextView) findViewById(R.id.textSmallDescript);
    }

    /**
     * 加载书籍信息
     * @param bookId
     */
    private void initBook(String bookId)
    {
        final String path = ApiAddress.getApiDomain() + "/client/ClientServlet?op=getBooksByid&id=" + bookId;


        AsyncHttpClient client = new AsyncHttpClient();
        client.get(path, new AsyncHttpResponseHandler()
        {
            @Override
            public void onFailure(int statusCode, Header[] arg1, byte[] arg2, Throwable arg3)
            {
                LoadDialogUtils.hidden();
            }

            @Override
            public void onSuccess(int arg0, Header[] arg1, byte[] responseBody)
            {
                String body = new String(responseBody);

                try
                {
                    JSONObject obj = new JSONObject(body);

                    int id = obj.getInt("id");
                    int number = obj.getInt("number");
                    double price = obj.getDouble("price");

                    bookNumber = number;

                    String address = obj.getString("address");
                    String author = obj.getString("author");
                    String categoryName = obj.getString("categoryName");
                    String descript = obj.getString("descript");
                    String imagesSrc = obj.getString("imagesSrc");
                    String isbn = obj.getString("isbn");
                    String name = obj.getString("name");
                    String publisherName = obj.getString("publisherName");


                    LoadDialogUtils.hidden();

                    imageBook.setImageUrl(imagesSrc);
                    textBookName.setText(name);
                    textNumber.setText(number + "");
                    textPrice.setText("￥" + price);
                    textAuthor.setText(author);
                    textPublisher.setText(publisherName);
                    textCatrgory.setText(categoryName);
                    textISBN.setText(isbn);
                    textAddress.setText(address);
                    textDescript.setText(descript.length() <= 0 ? "暂无相关描述" : descript);
                    textSmallDescript.setText(descript.length() > 20 ? descript.substring(0, 20) + "..." : descript.length() <= 0 ? "暂无相关描述" : descript);


                } catch (Exception e)
                {
                    // TODO: handle exception
                }

            }
        });


    }


    /**
     * 添加到借书单
     * @param v
     */
    public void addBook(View v)
    {
        //添加到借书单
        String ids = SPUtils.getString(AppConsrants.BORROW_LIST_ID, "", BookActivity.this);
        if (!ids.contains(bookId + ""))
        {
            SPUtils.putString(AppConsrants.BORROW_LIST_ID, ids + "," + bookId, BookActivity.this);
        }

        ToastUtils.makeText(BookActivity.this, "书籍已成功添加到借书单");
    }

    /**
     * 借书
     * @param v
     */
    public void borrow(View v)
    {
        //立即借书
        Intent intent1 = new Intent(BookActivity.this, BorrowActivity.class);
        intent1.putExtra(AppConsrants.SCAN_BORROW_IDS, bookId + "");
        startActivity(intent1);

    }

    /**
     * 预定
     * @param v
     */
    public void needBook(View v)
    {
        if(bookNumber>=1)
        {
            ToastUtils.makeText(BookActivity.this,"此书籍库存充足，无需预定");
            return;
        }

        final String path = ApiAddress.getApiDomain() + "/client/ClientServlet?op=addorder&userId=" + bookId+"&bookId="+bookId;


        AsyncHttpClient client = new AsyncHttpClient();
        client.get(path, new AsyncHttpResponseHandler()
        {
            @Override
            public void onFailure(int statusCode, Header[] arg1, byte[] arg2, Throwable arg3)
            {

            }

            @Override
            public void onSuccess(int arg0, Header[] arg1, byte[] responseBody)
            {
                String body = new String(responseBody);

                try
                {
                    JSONObject obj = new JSONObject(body);

                    String status =obj.getString("status");

                    if("ok".equalsIgnoreCase(status))
                    {
                        ToastUtils.makeText(BookActivity.this,"预定成功，当有人归还时您将收到通知");
                    }

                } catch (Exception e)
                {
                    // TODO: handle exception
                }

            }
        });
    }


}

